import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { readBananaPhoneInfo, readCodeFile, readBinaryFile } from "./utils.js";
import {
  ListResourcesRequestSchema,
  ReadResourceRequestSchema,
  ListResourceTemplatesRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";

const server = new Server(
  {
    name: "resources-server",
    version: "0.1.0",
    description: "提供资源的MCP服务器",
  },
  {
    capabilities: {
      resources: {},
    },
  }
);

// 列出资源
server.setRequestHandler(ListResourcesRequestSchema, async () => {
  return {
    resources: [
      {
        uri: "bananaphone://info",
        name: "香蕉手机信息",
        description: "香蕉手机的产品介绍和特性",
        mimeType: "text/plain",
      },
      {
        uri: "image://books",
        name: "图书图片",
        description: "books.jpeg图片文件",
        mimeType: "image/jpeg",
      },
    ],
  };
});

// 列出资源模板
server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
  return {
    resourceTemplates: [
      {
        uriTemplate: "code://file/{filename}",
        name: "代码文件",
        description: "访问code目录下的JS文件的内容",
        mimeType: "text/javascript",
      },
    ],
  };
});

// 读取资源
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  // 无论是读取资源还是资源模板，都是 resources/read 方法
  // 这意味着我们需要在回调函数里面自己来做处理

  const { uri } = request.params;
  console.error("uri>>>", uri);

  if (uri === "bananaphone://info") {
    const content = await readBananaPhoneInfo("src/assets", "bananaphone.txt");
    return {
      contents: [
        {
          uri: uri,
          mimeType: "text/plain",
          text: content,
        },
      ],
    };
  }

  if (uri === "image://books") {
    // 读取图片资源
    const base64Data = await readBinaryFile("src/assets", "books.jpeg");
    return {
      contents: [
        {
          uri: uri,
          mimeType: "image/jpeg",
          text: base64Data,
        },
      ],
    };
  }

  if (uri.startsWith("code://file/")) {
    const uriObj = new URL(uri);
    // 获取最后一个部分：文件名
    const filename = uriObj.pathname.split("/").pop(); // 1.js、2.js

    if (!filename || !filename.endsWith(".js")) {
      throw new Error("请指定一个有效的.js文件");
    }

    const content = await readCodeFile(filename);

    return {
      contents: [
        {
          uri,
          mimeType: "text/javascript",
          text: content,
        },
      ],
    };
  }

  throw new Error(`未知的资源URI: ${uri}`);
});

const transport = new StdioServerTransport();
await server.connect(transport);
